<template>
  <div class="user-dashboard">
    <div class="welcome-card">
      <el-card class="welcome">
        <h2>欢迎回来，{{ userInfo.name || '用户' }}！</h2>
        <p>今天是 {{ currentDate }}，祝您身体健康，心情愉快！</p>
      </el-card>
    </div>
    
    <!-- 快捷操作 -->
    <div class="quick-actions">
      <h3>快捷操作</h3>
      <div class="actions-grid">
        <el-card class="action-card" @click="router.push('/user/appointments')">
          <div class="action-content">
            <el-icon class="action-icon" color="#409EFF"><Calendar /></el-icon>
            <div class="action-text">
              <h4>预约服务</h4>
              <p>预约护理、体检等服务</p>
            </div>
          </div>
        </el-card>
        
        <el-card class="action-card" @click="router.push('/user/health')">
          <div class="action-content">
            <el-icon class="action-icon" color="#67C23A"><Document /></el-icon>
            <div class="action-text">
              <h4>健康记录</h4>
              <p>查看健康数据记录</p>
            </div>
          </div>
        </el-card>
        
        <el-card class="action-card" @click="router.push('/user/profile')">
          <div class="action-content">
            <el-icon class="action-icon" color="#E6A23C"><User /></el-icon>
            <div class="action-text">
              <h4>个人信息</h4>
              <p>修改个人资料</p>
            </div>
          </div>
        </el-card>
        
        <el-card class="action-card" @click="handleEmergencyCall">
          <div class="action-content">
            <el-icon class="action-icon" color="#F56C6C"><Phone /></el-icon>
            <div class="action-text">
              <h4>紧急呼叫</h4>
              <p>一键联系紧急联系人</p>
            </div>
          </div>
        </el-card>
      </div>
    </div>
    
    <!-- 最近预约 -->
    <div class="recent-appointments">
      <h3>最近预约</h3>
      <el-card>
        <div v-if="recentAppointments.length === 0" class="no-data">
          <el-empty description="暂无预约记录" />
        </div>
        <div v-else>
          <div 
            v-for="appointment in recentAppointments" 
            :key="appointment.id"
            class="appointment-item"
          >
            <div class="appointment-info">
              <div class="appointment-type">
                <el-tag :type="getServiceTypeColor(appointment.serviceType)">
                  {{ getServiceTypeLabel(appointment.serviceType) }}
                </el-tag>
              </div>
              <div class="appointment-details">
                <p class="appointment-time">{{ appointment.appointmentDate }} {{ appointment.appointmentTime }}</p>
                <p class="appointment-staff">服务人员：{{ appointment.staffName }}</p>
              </div>
            </div>
            <div class="appointment-status">
              <el-tag :type="getStatusType(appointment.status)">
                {{ getStatusLabel(appointment.status) }}
              </el-tag>
            </div>
          </div>
        </div>
      </el-card>
    </div>
    
    <!-- 健康提醒 -->
    <div class="health-reminders">
      <h3>健康提醒</h3>
      <el-card>
        <div class="reminder-list">
          <div class="reminder-item">
            <el-icon color="#E6A23C"><Warning /></el-icon>
            <span>建议定期测量血压，保持健康监测</span>
          </div>
          <div class="reminder-item">
            <el-icon color="#409EFF"><InfoFilled /></el-icon>
            <span>记得按时服药，如有不适请及时联系医生</span>
          </div>
          <div class="reminder-item">
            <el-icon color="#67C23A"><SuccessFilled /></el-icon>
            <span>保持规律作息，适量运动有益健康</span>
          </div>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { 
  Calendar, 
  Document, 
  User, 
  Phone,
  Warning,
  InfoFilled,
  SuccessFilled
} from '@element-plus/icons-vue'

// API 基础URL
const API_BASE_URL = 'http://localhost:8080/api'

const router = useRouter()

// 获取当前用户ID
const getCurrentUserId = () => {
  try {
    const userInfoStr = localStorage.getItem('userInfo')
    if (userInfoStr) {
      const userInfo = JSON.parse(userInfoStr)
      return userInfo.id
    }
    return null
  } catch (error) {
    console.error('获取用户ID失败:', error)
    return null
  }
}

// 根据用户ID获取老人ID
const getElderlyIdByUserId = async (userId: number) => {
  try {
    const response = await fetch(`${API_BASE_URL}/elderly/user/${userId}`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json'
      }
    })
    
    if (response.ok) {
      const result = await response.json()
      if (result.code === 200) {
        return result.data
      }
    }
    throw new Error('未找到对应的老人信息')
  } catch (error) {
    console.error('获取老人ID失败:', error)
    throw error
  }
}

const loading = ref(false)
const userInfo = ref({
  name: '用户',
  age: 0,
  phone: ''
})

const currentDate = ref('')
const recentAppointments = ref<any[]>([])

// 格式化时间
const formatDateTime = (dateTime: string) => {
  if (!dateTime) return ''
  const date = new Date(dateTime)
  return date.toLocaleDateString('zh-CN')
}

// 加载用户信息
const loadUserInfo = async () => {
  try {
    const userId = getCurrentUserId()
    if (!userId) {
      return
    }
    
    const elderlyData = await getElderlyIdByUserId(userId)
    userInfo.value = {
      name: elderlyData.name || '用户',
      age: elderlyData.age || 0,
      phone: elderlyData.phone || ''
    }
  } catch (error) {
    console.error('加载用户信息失败:', error)
    // 使用默认值，不显示错误消息
  }
}

// 加载最近预约
const loadRecentAppointments = async () => {
  try {
    const userId = getCurrentUserId()
    if (!userId) {
      return
    }
    
    const elderlyData = await getElderlyIdByUserId(userId)
    
    const params = new URLSearchParams()
    params.append('page', '0')
    params.append('size', '5')
    params.append('elderlyId', elderlyData.id.toString())
    
    const response = await fetch(`${API_BASE_URL}/appointments?${params.toString()}`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json'
      }
    })
    
    if (!response.ok) {
      throw new Error('获取预约数据失败')
    }
    
    const result = await response.json()
    if (result.code === 200) {
      const appointments = result.data.content.map((appointment: any) => ({
        id: appointment.id,
        serviceType: appointment.serviceType,
        appointmentDate: formatDateTime(appointment.appointmentDate),
        appointmentTime: appointment.appointmentTime,
        staffName: appointment.staffName || '待分配',
        status: appointment.status
      }))
      
      recentAppointments.value = appointments.slice(0, 3) // 只显示最近3个
    }
  } catch (error) {
    console.error('加载预约数据失败:', error)
    // 不显示错误消息，保持空数组
  }
}

// 获取服务类型标签
const getServiceTypeLabel = (type: string) => {
  const typeMap: { [key: string]: string } = {
    physical_exam: '体检',
    nursing: '护理',
    meal_delivery: '送餐',
    cleaning: '清洁',
    companionship: '陪伴'
  }
  return typeMap[type] || type
}

// 获取服务类型颜色
const getServiceTypeColor = (type: string) => {
  const colorMap: { [key: string]: string } = {
    physical_exam: 'success',
    nursing: 'primary',
    meal_delivery: 'warning',
    cleaning: 'info',
    companionship: 'danger'
  }
  return colorMap[type] || 'default'
}

// 获取状态标签
const getStatusLabel = (status: string) => {
  const statusMap: { [key: string]: string } = {
    pending: '待确认',
    confirmed: '已确认',
    in_progress: '进行中',
    completed: '已完成',
    cancelled: '已取消'
  }
  return statusMap[status] || status
}

// 获取状态类型
const getStatusType = (status: string) => {
  const typeMap: { [key: string]: string } = {
    pending: 'warning',
    confirmed: 'primary',
    in_progress: 'success',
    completed: 'success',
    cancelled: 'danger'
  }
  return typeMap[status] || 'info'
}

// 紧急呼叫
const handleEmergencyCall = () => {
  ElMessage.info('正在联系紧急联系人...')
  // 这里可以实现实际的紧急呼叫功能
}

// 获取当前日期
const getCurrentDate = () => {
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')
  const weekdays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']
  const weekday = weekdays[now.getDay()]
  
  currentDate.value = `${year}年${month}月${day}日 ${weekday}`
}

onMounted(async () => {
  getCurrentDate()
  await loadUserInfo()
  await loadRecentAppointments()
})
</script>

<style scoped>
.user-dashboard {
  padding: 0;
}

.welcome-card {
  margin-bottom: 24px;
}

.welcome {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
}

.welcome h2 {
  margin: 0 0 10px 0;
  font-size: 24px;
  font-weight: 500;
}

.welcome p {
  margin: 0;
  opacity: 0.9;
  font-size: 16px;
}

.quick-actions {
  margin-bottom: 24px;
}

.quick-actions h3 {
  margin: 0 0 16px 0;
  color: #333;
  font-size: 18px;
  font-weight: 500;
}

.actions-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 16px;
}

.action-card {
  cursor: pointer;
  transition: all 0.3s;
  border: 1px solid #ebeef5;
}

.action-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.action-content {
  display: flex;
  align-items: center;
  padding: 8px 0;
}

.action-icon {
  font-size: 32px;
  margin-right: 16px;
}

.action-text h4 {
  margin: 0 0 4px 0;
  font-size: 16px;
  color: #333;
}

.action-text p {
  margin: 0;
  font-size: 14px;
  color: #666;
}

.recent-appointments {
  margin-bottom: 24px;
}

.recent-appointments h3 {
  margin: 0 0 16px 0;
  color: #333;
  font-size: 18px;
  font-weight: 500;
}

.no-data {
  padding: 20px 0;
}

.appointment-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 0;
  border-bottom: 1px solid #ebeef5;
}

.appointment-item:last-child {
  border-bottom: none;
}

.appointment-info {
  display: flex;
  align-items: center;
  flex: 1;
}

.appointment-type {
  margin-right: 16px;
}

.appointment-details p {
  margin: 0 0 4px 0;
  color: #333;
}

.appointment-time {
  font-weight: 500;
}

.appointment-staff {
  font-size: 14px;
  color: #666;
}

.health-reminders h3 {
  margin: 0 0 16px 0;
  color: #333;
  font-size: 18px;
  font-weight: 500;
}

.reminder-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.reminder-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 6px;
  font-size: 14px;
  color: #333;
}
</style> 